'use client';

import { use, useEffect, useRef } from 'react';
import { useDonationHub } from '@/hooks/useDonationHub';
import './style.scss';

type Props = {
	params: Promise<{ channelSID: string }>;
};

// 기본 스타일 설정 (TODO: API에서 DonationGoalConfig 조회)
const DEFAULT_CONFIG = {
	barColor: '#FF6B35',
	barBackgroundColor: '#333333',
	barHeightPx: 30,
	titleFontSizePx: 18,
	titleFontColor: '#FFFFFF',
	amountFontSizePx: 14,
	amountFontColor: '#CCCCCC',
	isShowPercent: true
};

export default function GoalPage({ params }: Props) {
	const { channelSID } = use(params);
	const hubUrl = process.env.NEXT_PUBLIC_API_URL + '/hubs/donation';
	const { goalProgress } = useDonationHub(channelSID, hubUrl);
	const widgetRef = useRef<HTMLDivElement>(null);

	const cfg = DEFAULT_CONFIG;

	useEffect(() => {
		if (!widgetRef.current || !goalProgress) return;
		const el = widgetRef.current;
		el.style.setProperty('--goal-title-font-size', `${cfg.titleFontSizePx}px`);
		el.style.setProperty('--goal-title-color', cfg.titleFontColor);
		el.style.setProperty('--goal-bar-height', `${cfg.barHeightPx}px`);
		el.style.setProperty('--goal-bar-bg-color', cfg.barBackgroundColor);
		el.style.setProperty('--goal-bar-color', cfg.barColor);
		el.style.setProperty('--goal-bar-fill-width', `${Math.min(goalProgress.percent, 100)}%`);
		el.style.setProperty('--goal-amount-font-size', `${cfg.amountFontSizePx}px`);
		el.style.setProperty('--goal-amount-color', cfg.amountFontColor);
	}, [goalProgress, cfg]);

	if (!goalProgress) {
		return <div className="goal-widget goal-widget--loading">목표 데이터 대기 중...</div>;
	}

	const { title, currentAmount, targetAmount, percent } = goalProgress;

	return (
		<div ref={widgetRef} className="goal-widget">
			<div className="goal-title">
				{title}
			</div>

			<div className="goal-bar-wrapper">
				<div className="goal-bar-bg">
					<div className="goal-bar-fill" />
				</div>
				<div className="goal-bar-text">
					{currentAmount.toLocaleString()}원 / {targetAmount.toLocaleString()}원
					{cfg.isShowPercent && ` (${percent}%)`}
				</div>
			</div>
		</div>
	);
}